package com.xgkj.diyiketang.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.Text;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.data.HuoDongInfo;
import com.xgkj.diyiketang.data.OrderInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.BuildOrderTask;
import com.xgkj.diyiketang.task.GetVerifyCodeTask;
import com.xgkj.diyiketang.task.YueZhiFuTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeiXinPay;
import com.xgkj.diyiketang.wxapi.WXPayEntryActivity;
import com.xgkj.diyiketang.R;

public class LijibaomingActivity extends BaseActivity implements View.OnClickListener{
    private String TAG = getClass().getSimpleName();
    private Context mContext;
    private static final int PHONE_LENGTH = 11;
    private static final String PHONE_REGEX = "1[34578]\\d{9}";
    private static final int CODE_LENGTH = 6;
    private TextView hdNameText;
    private TextView hdPriceText;
    private TextView hdTimeText;
    private EditText hdPhoneText;
    private EditText codeEdit;
    private LinearLayout codeLayout;
    private ImageView codeLineImage;
    private HuoDongInfo hdInfo;
    private RelativeLayout lingqianLayout;
    private RelativeLayout weixinLayout;
    private TextView feeText;
    private ImageButton zhifuBtn;
    private TextView codeBtn;
    private ImageView weixin_check;
    private ImageView lingqian_check;
    private TimeCount time;
    String mPhone;
    private int getCodeTaskId = -1;
    private int mZhifuType = -1;
    private String code;
    private int yuezhifuTaskId = -1;
    private int orderTaskId = -1;
    private String mObjectId;
    private String mMoney;
    private OrderInfo odinfo;
    private String mOrderNo;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private WeixinReceive mWeiXinReceive;
    private String orderBody = "第一课堂";

    private Button money1;
    private Button money6;
    private Button money30;
    private Button money68;
    private Button money198;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lijibaoming);
        mContext = this;
        time = new TimeCount(90000, 1000);
        msgApi.registerApp(ProtocolConst.APP_ID);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null){
            hdInfo = (HuoDongInfo) intent.getSerializableExtra("HUODONGINFO");
        }

        if (hdInfo == null){
            finish();return;
        }
        mMoney = hdInfo.getFee();
        mObjectId = hdInfo.getActivityId();
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        hdNameText = (TextView) findViewById(R.id.huodong_name);
        hdNameText.setText(hdInfo.getActivityTitle());
        hdPriceText = (TextView) findViewById(R.id.huodong_price);
        feeText = (TextView) findViewById(R.id.fee);
        hdPriceText.setText(hdInfo.getFee()+"元");
        feeText.setText(hdInfo.getFee());
        hdTimeText = (TextView) findViewById(R.id.huodong_time);
        hdTimeText.setText(hdInfo.getStartTime());
        hdPhoneText = (EditText) findViewById(R.id.huodong_phone);
        codeLayout = (LinearLayout) findViewById(R.id.code_layout);
        codeEdit = (EditText) findViewById(R.id.forget_code);
        codeBtn = (TextView) findViewById(R.id.forget_code_button);
        codeBtn.setOnClickListener(this);
        codeLineImage = (ImageView) findViewById(R.id.phone_line);
        //发送验证码是否显示
        String phone = hdInfo.getPhoneNum();
        if (!ViewUtil.isNull(phone)){
            codeLayout.setVisibility(View.GONE);
            hdPhoneText.setText(phone);
            hdPhoneText.setEnabled(false);
            hdPhoneText.setFocusable(false);
            hdPhoneText.setFocusableInTouchMode(false);
            codeLineImage.setVisibility(View.GONE);

        }else {
            hdPhoneText.setEnabled(true);
            codeLayout.setVisibility(View.VISIBLE);
            codeLayout.setVisibility(View.VISIBLE);
        }

        lingqian_check = (ImageView) findViewById(R.id.lingqian_check);
        lingqianLayout = (RelativeLayout) findViewById(R.id.lingqian_layout);
        lingqianLayout.setOnClickListener(this);
        weixin_check = (ImageView) findViewById(R.id.weixin_check);
        weixinLayout = (RelativeLayout) findViewById(R.id.weixin_layout);
        weixinLayout.setOnClickListener(this);

        zhifuBtn = (ImageButton) findViewById(R.id.baoming_btn);
        zhifuBtn.setOnClickListener(this);
        mZhifuType = 0;
        weixin_check.setVisibility(View.VISIBLE);
        lingqian_check.setVisibility(View.GONE);

        money1 = (Button) findViewById(R.id.money1_btn);
        money1.setOnClickListener(this);
        money6 = (Button) findViewById(R.id.money6_btn);
        money6.setOnClickListener(this);
        money30 = (Button) findViewById(R.id.money30_btn);
        money30.setOnClickListener(this);
        money68 = (Button) findViewById(R.id.money68_btn);
        money68.setOnClickListener(this);
        money198 = (Button) findViewById(R.id.money198_btn);
        money198.setOnClickListener(this);

    }

    private void doWeixinPay() {
        if (!msgApi.isWXAppSupportAPI() || !msgApi.isWXAppInstalled()) {
            ToastUtil.showMessage(mContext, R.string.need_weixin_app);
            return;
        }

        if (mWeiXinReceive == null) {
            mWeiXinReceive = new WeixinReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXPayEntryActivity.WEIXIN_PAY_SUCCESS_ACTION);
            registerReceiver(mWeiXinReceive, filter);
        }
        new WeiXinPay(msgApi, LijibaomingActivity.this, mOrderNo, orderBody, mMoney);
    }

    private Handler alipayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    class WeixinReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isSuccess = intent.getBooleanExtra(ProtocolConst.WEIXINPAY_SUCCESS, false);
            if (isSuccess) {
                Intent wintent = new Intent(mContext, BaoMingChengGongActivity.class);
                wintent.putExtra("ORDERNO", mOrderNo);
                wintent.putExtra("FEE", mMoney);
                startActivity(wintent);
                finish();

            } else {

            }

            if (mWeiXinReceive != null) {
                unregisterReceiver(mWeiXinReceive);
                mWeiXinReceive = null;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWeiXinReceive != null) {
//            unregisterReceiver(mWeiXinReceive);
            mWeiXinReceive = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lingqian_layout:
                mZhifuType = 2;
                lingqian_check.setVisibility(View.VISIBLE);
                weixin_check.setVisibility(View.GONE);
                break;

            case R.id.weixin_layout:
                mZhifuType = 0;
                weixin_check.setVisibility(View.VISIBLE);
                lingqian_check.setVisibility(View.GONE);
                break;

            case R.id.baoming_btn:
                PalLog.e(TAG,"点击支付");
                if (checkInput()){
                    if (mZhifuType==2) {
                            doYueZhifu();
                        } else if (mZhifuType == 0){
                            getOrder();
                        }
                }
                break;

            case R.id.forget_code_button:
                if (checkInputBeforeSMS()) {
                    getPhoneCode();
                }
                break;
            case R.id.money1_btn:
                money1.setEnabled(false);
                money6.setEnabled(true);
                money30.setEnabled(true);
                money68.setEnabled(true);
                money198.setEnabled(true);
                mMoney = hdInfo.getFee();
                mMoney=String.valueOf(Integer.parseInt(mMoney)+1);
                feeText.setText(mMoney);
                break;

            case R.id.money6_btn:
                money1.setEnabled(true);
                money6.setEnabled(false);
                money30.setEnabled(true);
                money68.setEnabled(true);
                money198.setEnabled(true);
                mMoney = hdInfo.getFee();
                mMoney=String.valueOf(Integer.parseInt(mMoney)+6);
                feeText.setText(mMoney);
                break;

            case R.id.money30_btn:
                money1.setEnabled(true);
                money6.setEnabled(true);
                money30.setEnabled(false);
                money68.setEnabled(true);
                money198.setEnabled(true);
                mMoney = hdInfo.getFee();
                mMoney=String.valueOf(Integer.parseInt(mMoney)+30);
                feeText.setText(mMoney);
                break;
            case R.id.money68_btn:
                money1.setEnabled(true);
                money6.setEnabled(true);
                money30.setEnabled(true);
                money68.setEnabled(false);
                money198.setEnabled(true);
                mMoney = hdInfo.getFee();
                mMoney=String.valueOf(Integer.parseInt(mMoney)+68);
                feeText.setText(mMoney);
                break;
            case R.id.money198_btn:
                money1.setEnabled(true);
                money6.setEnabled(true);
                money30.setEnabled(true);
                money68.setEnabled(true);
                money198.setEnabled(false);
                mMoney = hdInfo.getFee();
                mMoney=String.valueOf(Integer.parseInt(mMoney)+198);
                feeText.setText(mMoney);
                break;
        }
    }

    private void doYueZhifu() {
        if (yuezhifuTaskId != -1) {
            return;
        }
        YueZhiFuTask task = new YueZhiFuTask(mObjectId, "1", mMoney,null);
        task.addListener(new ForgetPswTaskEventListener(mContext));
        yuezhifuTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void getOrder() {
        BuildOrderTask task = new BuildOrderTask(mObjectId, "1", mMoney, String .valueOf(mZhifuType),null,null,null,null,null,null,null);
//        BuildOrderTask task = new BuildOrderTask("",  "1", money, channelType);
        task.addListener(new ForgetPswTaskEventListener(mContext));
        orderTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private boolean checkInput(){
        if (checkInputBeforeSMS()){
            if (codeLayout.getVisibility() == View.VISIBLE) {
                code = codeEdit.getText().toString();
                if (ViewUtil.isNull(code) || code.length() != CODE_LENGTH) {
                    Toast.makeText(mContext, R.string.no_code, Toast.LENGTH_SHORT)
                            .show();
                    return false;
                }
                return true;
            }else if (mZhifuType == -1){
                Toast.makeText(mContext, R.string.no_check_pay, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            return true;
        }
        return false;
    }


    private boolean checkInputBeforeSMS() {
        mPhone = hdPhoneText.getText().toString();
        if (TextUtils.isEmpty(mPhone) || mPhone.length() != PHONE_LENGTH
                || !mPhone.matches(PHONE_REGEX)) {
            Toast.makeText(mContext, R.string.no_phone, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private void getPhoneCode() {
        GetVerifyCodeTask task = new GetVerifyCodeTask(mPhone, "2");
        task.addListener(new ForgetPswTaskEventListener(mContext));
        getCodeTaskId = getEatShowApp().getTaskManager().addTask(task);
        time.start();
    }



    class ForgetPswTaskEventListener extends ShowToastTaskEventListener

    {

        public ForgetPswTaskEventListener(Context context) {
        super(context);
    }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
             super.handleTaskCompleted(taskId, result, data);
            if (orderTaskId == taskId) {
                orderTaskId = -1;
                if (data != null) {
                    odinfo = (OrderInfo) data;
                }
                mOrderNo = odinfo.getOrderNo();
                doWeixinPay();

//                mZhifuType = odinfo.getPayChannel();
//                if (mZhifuType.equals(ALIPAY_TYPE)) {
//                    doAliPay();
//
//                } else if (mZhifuType.equals(WEIXINPAY_TYPE)) {
//                    doWeixinPay();
//
//                }
            }else if(yuezhifuTaskId == taskId){
                if (data != null) {
                    odinfo = (OrderInfo) data;
                    mOrderNo = odinfo.getOrderNo();
                    Intent intent = new Intent(mContext, BaoMingChengGongActivity.class);
                    intent.putExtra("ORDERNO", mOrderNo);
                    intent.putExtra("FEE", mMoney);
                    startActivity(intent);
                    finish();
                }
            }

    }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
        super.handleTaskError(taskId, errorCode, errorMsg);
        if (taskId == getCodeTaskId) {
            getCodeTaskId = -1;
            time.cancelTime();
        }
    }

    }


    /**
     * 方法作用：倒计时
     */
    class TimeCount extends CountDownTimer {

        // 参数依次为总时长,和计时的时间间隔
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            codeBtn.setText(mContext.getString(R.string.get_vfcode));
            codeBtn.setClickable(true);
            codeBtn.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            codeBtn.setClickable(false);
            codeBtn.setEnabled(false);
            codeBtn.setText(String.format(
                    mContext.getString(R.string.get_vfcode_new),
                    millisUntilFinished / 1000));
        }

        public void cancelTime() {// 取消计时
            time.cancel();
            codeBtn.setText(mContext.getString(R.string.get_vfcode));
            codeBtn.setClickable(true);
            codeBtn.setEnabled(true);
        }

    }
}
